package de.connecttext.deprecated;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import de.connecttext.application.Constants;
import de.connecttext.dao.solr.SolrDao;
import de.connecttext.dao.solr.WikipediaSolrDao;
import de.connecttext.dao.sql.SqlConnection;
import de.connecttext.dao.sql.SqlDao;
import de.connecttext.exception.SqlAccessException;
import de.connecttext.model.TagVector;
import de.connecttext.model.TextDocument;

public class OriginalTermRecovery extends Thread {

	public void run() {

		SolrDao solrDao = new WikipediaSolrDao();
		try {
			SqlDao sqlDao = SqlDao.getInstance();
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		// Count of documents already processed
		int documentCount = 0;
		// id = 0
		// Count of documents, but more recent
		int currentDocumentCount = 0;

		while (true) {
			try {
				Connection db = SqlConnection.open();
				// documentCount is the difference between the count of
				// documents in
				// the database right now and the count in the last iteration,
				// since
				// the Mainthread should be busy writng Documents to the
				// Database
				// right now

				Statement countStatement = db.createStatement();
				ResultSet countResultSet = countStatement
						.executeQuery("SELECT COUNT(id) as count FROM `document`");
				int newCount = 0;
				while (countResultSet.next()) {
					newCount = countResultSet.getInt("count");
				}
				countStatement.close();

				int databaseResetCounter = 1;

				if (newCount == documentCount) {
					// If there a no new documents added, wait 5 seconds and
					// check
					// again
					int sleepyTime = 5000;
					Thread.sleep(sleepyTime);
					System.out
							.println("Found no Documents yet.. sleeping... for "
									+ sleepyTime + " milliseconds...");
				} else {
					// There are documents added!
					for (int i = documentCount + 1; i <= newCount; i++) {

						databaseResetCounter++;

						if (databaseResetCounter > Constants.SQL_DOCUMENTS_BUFFER_SIZE) {

							db.close();
							db = SqlConnection.open();
							currentDocumentCount += databaseResetCounter;
							System.out.println("Documents Refined: "
									+ currentDocumentCount);
							databaseResetCounter = 0;

						}

						PreparedStatement documentStatement = db
								.prepareStatement("SELECT document_tag.id, document.path, tag.tag, document_tag.tag_alt FROM `document` LEFT JOIN document_tag ON document.id = document_id LEFT JOIN tag ON tag.id = tag_id WHERE document.id = ?");
						documentStatement.setInt(1, i);
						ResultSet documentResultSet = documentStatement
								.executeQuery();

						// This iterates over all Tags attributed to the
						// document
						String path = null;
						while (documentResultSet.next()) {
							if (path == null) path = documentResultSet.getString("path");

							int documentTagId = documentResultSet.getInt("id");
							// Path should be the same anyways
							String tag = documentResultSet.getString("tag");

							// Some Tags have encoding erros. Throw those away
							// please!
							if (tag != null && tag.contains("?"))
								continue;
							String tagAlt = documentResultSet
									.getString("tag_alt");

							if ((tag != null && !tag.isEmpty())
									&& (tagAlt == null || tagAlt.isEmpty())) {
								tagAlt = solrDao
										.retrieveOriginalTerm(path, tag);
								//System.out.println(tag + " " + tagAlt);
								PreparedStatement documentUpdateStatement = db
										.prepareStatement("UPDATE document_tag SET tag_alt = ? WHERE document_tag.id = ?");

								documentUpdateStatement.setString(1, tagAlt);
								documentUpdateStatement
										.setInt(2, documentTagId);
								try {
								documentUpdateStatement.executeUpdate();
								} catch (Exception e){
									System.out.println("ERROR: Konnte folgendes nicht in die Datenbank schreiben: " + tagAlt);
								}
							}

							// System.out.println(i + " " + path + ": Tag " +
							// tag + " successfulls recovered to " + tagAlt );

						}
						// System.out.println(i +
						// ". Document successfully recovered");
						documentStatement.close();

					} // end for documentCount

					// All new documents are processed
					documentCount = newCount;

				}

				db.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

		} // end while

	}
}
